package cn.cosmosx.base.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import cn.cosmosx.base.handler.ServletErrorHandler;

import javax.servlet.Servlet;
import java.util.stream.Collectors;

/**
 * 自定义Servlet异常处理配置类
 * 注入Bean的形式参考{@linkplain ErrorMvcAutoConfiguration}
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
// 在主WebMvcAutoConfiguration之前加载，以便错误视图可用
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ServerProperties.class, WebMvcProperties.class})
public class ServletErrorConfiguration {

    private final ServerProperties serverProperties;

    public ServletErrorConfiguration(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Bean
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

    /**
     * Servlet自定义异常处理器
     *
     * @param errorAttributes
     * @param errorViewResolvers
     * @return
     */
    @Bean
    public ServletErrorHandler servletFilterErrorController(
            ErrorAttributes errorAttributes,
            ObjectProvider<ErrorViewResolver> errorViewResolvers) {
        return new ServletErrorHandler(errorAttributes,
                serverProperties,
                errorViewResolvers.orderedStream().collect(Collectors.toList()));
    }
}
